package com.southminority.ethnic.service.token.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.southminority.ethnic.enums.RedisKeyEnum;
import com.southminority.ethnic.pojo.User;
import com.southminority.ethnic.service.redis.RedisService;
import com.southminority.ethnic.service.token.TokenService;
import com.southminority.ethnic.service.user.UserService;
import com.southminority.ethnic.service.user.impl.UserServiceImpl;
import com.southminority.ethnic.until.JsonUtil;
import com.southminority.ethnic.until.NumberUntil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Token验证服务实现类
 * 
 * @author SouthMinority
 */
@Slf4j
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    @Override
    public User validateToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            return null;
        }

        try {
            // 从Redis中获取用户信息
            String userJson = redisService.redisGetValue(RedisKeyEnum.USER_TOKEN.getKeyPrefix() + token);
            
            if (userJson == null) {
                log.warn("Token在Redis中不存在: {}", token);
                return null;
            }

            // 检查token是否即将过期
            Long expireTime = redisService.redisGetExpireTime(
                RedisKeyEnum.USER_TOKEN.getKeyPrefix() + token, 
                RedisKeyEnum.USER_TOKEN.getTimeUnit()
            );

            if (expireTime == null || expireTime <= 0) {
                log.warn("Token已过期: {}", token);
                return null;
            }

            // 解析用户信息
            User user = JsonUtil.fromJson(userJson, User.class);
            if (user == null) {
                log.warn("无法解析用户信息: {}", userJson);
                return null;
            }

            // 验证用户是否仍然存在
            User dbUser = userService.getById(user.getId());
            if (dbUser == null) {
                log.warn("用户不存在: {}", user.getId());
                return null;
            }

            return user;

        } catch (JsonProcessingException e) {
            log.error("解析用户信息失败", e);
            return null;
        } catch (Exception e) {
            log.error("验证token失败", e);
            return null;
        }
    }

    @Override
    public boolean isTokenValid(String token) {
        return validateToken(token) != null;
    }

    private static Integer tokenRemainTime;
    @Value("${self.redis.token-remain-life-cycle}")
    public void setTokenRemainTime(Integer tokenRemainTime) {
        TokenServiceImpl.tokenRemainTime = tokenRemainTime;
    }

    @Override
    public String refreshTokenIfNeeded(String token) {
        try {
            // 检查token是否即将过期（剩余时间小于5H）
            Long expireTime = redisService.redisGetExpireTime(
                RedisKeyEnum.USER_TOKEN.getKeyPrefix() + token, 
                RedisKeyEnum.USER_TOKEN.getTimeUnit()
            );

            if (expireTime != null && expireTime >= 0 && expireTime <= tokenRemainTime) {
                // 获取用户信息
                User user = validateToken(token);
                if (user != null) {
                    Boolean b= redisService.expire(
                            RedisKeyEnum.USER_TOKEN.getKeyPrefix() + token,
                            RedisKeyEnum.USER_TOKEN.getExpireTime(),
                            RedisKeyEnum.USER_TOKEN.getTimeUnit()
                    );
//                    if ( b) {
//                        log.info("Token已刷新，用户ID: {}", user.getId());
//                    }
//                    else {
//                        log.error("Token刷新失败，用户ID: {}", user.getId());
//                    }
                }
            }
            
            return token; // 如果不需要刷新，返回原token
            
        } catch (Exception e) {
            //log.error("刷新token失败", e);
            return token;
        }
    }

    @Override
    public void invalidateToken(String token) {
        try {
            // 从Redis中删除token
            redisService.redisDelete(RedisKeyEnum.USER_TOKEN.getKeyPrefix() + token);
            log.info("Token已失效: {}", token);
        } catch (Exception e) {
            log.error("使token失效失败", e);
        }
    }
} 